package com.ww.microrpc.netty.handler;

import com.ww.microrpc.netty.protocol.Message;
import com.ww.microrpc.netty.serializer.Serializer;
import com.ww.microrpc.netty.serializer.SerializerFactory;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * RPC Encoder ( RpcMessage to Byte )
 *
 * @author ww
 */
public class RpcEncoderHandler extends MessageToByteEncoder<Message> {

    private static final Logger logger = LoggerFactory.getLogger(RpcEncoderHandler.class);

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Message message, ByteBuf byteBuf) throws Exception {

        try {
            int serializerType = message.getSerializerType();
            Serializer serializer = SerializerFactory.create(serializerType);
            byte[] data = serializer.serialize(message);

            byteBuf.writeInt(data.length);
            byteBuf.writeByte(message.getMessageType());
            byteBuf.writeByte(serializerType);
            byteBuf.writeByte(message.getVersion());
            byteBuf.writeByte(message.getVersion());
            byteBuf.writeInt(message.getRequestId());
            byteBuf.writeBytes(data);

        } catch (Exception ex) {
            logger.error("Encode error: ", ex.getMessage(), ex);
        }
    }
}
